package run.bottle.app.service.impl;

import cn.hutool.core.lang.Validator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import run.bottle.app.exception.BadRequestException;
import run.bottle.app.exception.NotFoundException;
import run.bottle.app.model.entity.SysUser;
import run.bottle.app.security.context.SecurityContextHolder;
import run.bottle.app.security.token.AuthToken;
import run.bottle.app.security.util.SecurityUtils;
import run.bottle.app.service.AdminService;
import run.bottle.app.service.UserService;
import run.bottle.app.utils.BottleUtils;
import run.bottle.app.utils.RedisUtil;

import java.util.concurrent.TimeUnit;

/**
 * Admin service implementation.
 *
 * @author Lycheng
 */
@Slf4j
@Service
public class AdminServiceImpl implements AdminService {

    private final UserService userService;

    private final RedisUtil redisUtil;

    public AdminServiceImpl(
            UserService userService,
            RedisUtil redisUtil) {
        this.userService = userService;
        this.redisUtil = redisUtil;
    }


    @Override
    public SysUser authenticate(String username, String password) {

        Assert.notNull(username, "Login username must not be null");
        Assert.notNull(password, "Login password must not be null");

        String mismatchTip = "用户名或者密码不正确";

        final SysUser user;

        try {
            // Get user by username or email
            user = Validator.isEmail(username) ?
                    userService.getByEmailOfNonNull(username) : userService.getByUsernameOfNonNull(username);
        } catch (NotFoundException e) {
            log.error("Failed to find user by name: " + username);
            throw new BadRequestException(mismatchTip);
        }

        if (!userService.passwordMatch(user, password)) {
            throw new BadRequestException(mismatchTip);
        }

        return user;
    }

    @Override
    public AuthToken authCodeCheck(String username, String password) {

        // get user
        final SysUser user = this.authenticate(username,password);

        // todo check authCode

        if (SecurityContextHolder.getContext().isAuthenticated()) {
            // If the user has been logged in
            throw new BadRequestException("您已登录，请不要重复登录");
        }

        // 生成新令牌
        return buildAuthToken(user);
    }

    /**
     * Builds authentication token.
     *
     * @param user user info must not be null
     * @return authentication token
     */
    @NonNull
    private AuthToken buildAuthToken(@NonNull SysUser user) {
        Assert.notNull(user, "User must not be null");

        // Generate new token
        AuthToken token = new AuthToken();

        token.setAccessToken(BottleUtils.randomUUIDWithoutDash());
        token.setExpiredIn(ACCESS_TOKEN_EXPIRED_SECONDS);
        token.setRefreshToken(BottleUtils.randomUUIDWithoutDash());
        System.out.println(token.getAccessToken());
        // Cache those tokens, just for clearing
        redisUtil.set(SecurityUtils.buildAccessTokenKey(user), token.getAccessToken(), TimeUnit.SECONDS.toMillis(ACCESS_TOKEN_EXPIRED_SECONDS));
        redisUtil.set(SecurityUtils.buildRefreshTokenKey(user), token.getRefreshToken(), TimeUnit.DAYS.toMillis(REFRESH_TOKEN_EXPIRED_DAYS));

        // Cache those tokens with user id
        redisUtil.set(SecurityUtils.buildTokenAccessKey(token.getAccessToken()), user.getId(), TimeUnit.SECONDS.toMillis(ACCESS_TOKEN_EXPIRED_SECONDS));
        redisUtil.set(SecurityUtils.buildTokenRefreshKey(token.getRefreshToken()), user.getId(), TimeUnit.DAYS.toMillis(REFRESH_TOKEN_EXPIRED_DAYS));

        return token;
    }
}
